# Based on https://aur.archlinux.org/packages/mingw-w64-capnproto/
#
# Maintainer: Igor Matuszewski <xanewok@gmail.com>
# Contributors: Dave Reisner <dreisner@archlinux.org>
#               Matthias Blaicher <matthias@blaicher.com>
#               Severen Redwood <severen@shrike.me>
#               Igor Matuszewski <xanewok@gmail.com>

_realname=capnproto
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.8.0
pkgrel=3
pkgdesc="Cap'n Proto serialization/RPC system (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64')
url='https://capnproto.org/'
license=('MIT')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-zlib")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake")
source=("https://capnproto.org/capnproto-c++-${pkgver}.tar.gz")
sha512sums=('a32dbe6556a95761a5edc55237bd5558cb0ec08127f2fef1712076d5be4cd63e165a5d83b522307336bd3afeed1241f2c1e507830e8f12ac5dec78703a85417f')

prepare() {
  cd "${srcdir}/capnproto-c++-${pkgver}"
}

build() {
  [[ -d "${srcdir}/build-${CARCH}" ]] && rm -rf "${srcdir}/build-${CARCH}"
  mkdir -p "${srcdir}/build-${CARCH}" && cd "${srcdir}/build-${CARCH}"

MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G "MSYS Makefiles" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_BUILD_TYPE=Release \
    -DBUILD_SHARED_LIBS=ON \
    -DBUILD_TESTING=OFF \
    ../${_realname}-c++-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

package() {
  cd "${srcdir}/build-${CARCH}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target install

  local PREFIX_WIN="$(cygpath -wm ${MINGW_PREFIX})"

  for cmkfile in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/CapnProto/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i "${cmkfile}"
  done

  for pcfile in "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pcfile}"
  done

  # WARNING: Dirty hack to remove symbolic link
  rm "${pkgdir}${MINGW_PREFIX}/bin/capnpc.exe"
  cp "${pkgdir}${MINGW_PREFIX}/bin/capnp.exe" \
     "${pkgdir}${MINGW_PREFIX}/bin/capnpc.exe"
}
